package com.example.radiscache.controller;

import com.example.commonsinterface.dto.WeatherResponse;
import com.example.commonsinterface.po.City;
import com.example.radiscache.mapper.CityMapper;
import com.example.radiscache.service.WeatherSearch;
import com.example.radiscache.service.userMysqlCity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@RestController
@RequestMapping
public class WeatherController {

    @Autowired
    private WeatherSearch weatherSearch;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private userMysqlCity uMysqlCity;

    public WeatherResponse cacheWeatherData(){

        List<City> cityList = uMysqlCity.searchCity();
//        System.out.println(cityList.toString());
        WeatherResponse weatherResponse = null;
        for (City c : cityList) {
            System.out.println(c.getCode());
            weatherResponse=  weatherSearch.search(c.getCode());


            redisTemplate.opsForHash().put("weatherdata",c.getCode(),weatherResponse);
        }
        return weatherResponse;
    }

    @GetMapping("/searchWeather")
    public WeatherResponse searchWeather(@RequestParam String cityid){
        WeatherResponse w = null;
//        System.out.println("cityid:"+cityid);
        w=(WeatherResponse)redisTemplate.opsForHash().get("weatherdata",cityid);
//        System.out.println("w:-----------------------------"+w);
        if (w!=null){
            System.out.println("w:"+w.getResult());
        }
        if (w==null){
            w = cacheWeatherData();
        }
        return w;
    }
}
